import React, { Component } from 'react';
import { connect } from 'dva';
import { Card, Table, Input, Form, Radio, Button, Icon, message } from 'antd';
import { get } from 'lodash';
import { postArrange } from 'Services/publicServer.js';
import AddDriverModal from '../components/driverModal';

const STORE_NAME = 'workforce';
const FormItem = Form.Item;

@connect(state => ({
  [STORE_NAME]: state[STORE_NAME],
  loading: state.loading.effects[`${STORE_NAME}/fetchTableDataSource`],
}))
@Form.create()
class publicServerMessage extends Component {
  constructor(props) {
    super(props);
    window.scope = this;
  }

  state = {
    updateAble: false,
    visible: false,
  };

  componentDidMount() {
    this.fetchData();
  }

  getDataFromStore = key => (key ? this.props[STORE_NAME][key] : this.props[STORE_NAME]);

  /* 为dataSource添加index */
  addIndex = list => {
    return list.map((item, index) => ({
      ...item,
      index: index + 1,
    }));
  };

  fetchData() {
    const { dispatch } = this.props;
    dispatch({
      type: `${STORE_NAME}/fetchTableDataSource`,
    });
  }

  handleSubmit = e => {
    e.preventDefault();
    this.props.form.validateFields((err, value) => {
      this.props.dispatch({
        type: `${STORE_NAME}/updateFilterParams`,
        payload: value,
      });
    });
  };

  handleChange = ({ target: { value } }) => {
    const payload = {
      ...this.props.form.getFieldsValue(),
      direction: value,
    };
    this.props.dispatch({
      type: `${STORE_NAME}/updateFilterParams`,
      payload,
    });
  };

  handleAddSite = arr => {
    if (arr.length === 0) return false;
    const { tableDataSource } = this.getDataFromStore();
    this.props.dispatch({
      type: `${STORE_NAME}/SET_TABLE_DATA_SOURCE`,
      payload: [
        ...arr.filter(({ id }) => {
          for (let i = 0; i < tableDataSource.length; i += 1) {
            if (tableDataSource[i].id === id) return false;
          }
          return true;
        }),
        ...tableDataSource,
      ],
    });
    this.setState({ updateAble: true, visible: false });
  };

  handlesort = (direction, index) => {
    const { tableDataSource } = this.getDataFromStore();
    const now = tableDataSource[index];
    const next = tableDataSource[index + 1];
    const prev = tableDataSource[index - 1];
    if (direction === 'up') tableDataSource.splice(index, 2, next, now);
    else tableDataSource.splice(index - 1, 2, now, prev);
    this.props.dispatch({
      type: `${STORE_NAME}/SET_TABLE_DATA_SOURCE`,
      payload: tableDataSource,
    });
    this.setState({ updateAble: true });
  };

  handleUpdateLine = () => {
    const params = this.props.form.getFieldsValue();
    const driverList = this.getDataFromStore('tableDataSource').map(
      ({ dirverId, id, name }) => `${dirverId || id}:${name}`
    );
    if (!/[1234567]/.test(params.whatDay)) {
      message.error('请填写正确的星期：1-7');
      return false;
    }
    if (!params.line) {
      message.error('请填写线路名');
      return false;
    }
    postArrange({ ...params, driverList: `${driverList}` }).then(async res => {
      if (+get(res, 'code') === 0) {
        message.success('提交成功！');
        await this.setState({ updateAble: false });
        await this.props.dispatch({
          type: `${STORE_NAME}/updateFilterParams`,
          payload: params,
        });
      } else message.error(get(res, 'msg') || '提交失败！');
    });
  };

  handleReset = () => {
    this.fetchData();
    this.setState({ updateAble: false });
  };

  handleDel = index => {
    const { tableDataSource } = this.getDataFromStore();
    tableDataSource.splice(index, 1);
    this.props.dispatch({
      type: `${STORE_NAME}/SET_TABLE_DATA_SOURCE`,
      payload: tableDataSource,
    });
    this.setState({ updateAble: true });
  };

  columns = [
    {
      title: '排序',
      key: 'sort',
      width: '62px',
      render: (_, record, index) => {
        const { tableDataSource } = this.getDataFromStore();
        const last = tableDataSource.length - 1;
        return (
          <div style={{ textAlign: 'center' }}>
            {index !== 0 && (
              <div
                style={{ cursor: 'pointer' }}
                onClick={this.handlesort.bind(this, 'down', index)}
              >
                <Icon type="caret-up" />
              </div>
            )}
            {index !== last && (
              <div style={{ cursor: 'pointer' }} onClick={this.handlesort.bind(this, 'up', index)}>
                <Icon type="caret-down" />
              </div>
            )}
          </div>
        );
      },
    },
    {
      title: '序号',
      width: '80px',
      key: 'index',
      dataIndex: 'index',
      render: text => {
        const { tableDataSource } = this.getDataFromStore();
        const l = tableDataSource.length;
        let indexText = `第${text}班`;
        if (+text === 1) indexText = '早班车';
        if (+text === l) indexText = '末班车';
        return <span>{indexText}</span>;
      },
    },
    {
      title: '司机',
      key: 'name',
      dataIndex: 'name',
    },
    {
      title: '操作',
      key: 'gener',
      width: '65px',
      render: (_, record, index) => (
        <span>
          <a onClick={this.handleDel.bind(this, index)}>删除</a>
        </span>
      ),
    },
  ];

  render() {
    const { columns, addIndex } = this;
    const { tableDataSource: dataSource, filterParams } = this.getDataFromStore();
    const { getFieldDecorator } = this.props.form;

    return (
      <div>
        <Card
          title="排班管理"
          extra={
            <div>
              <Button
                style={{ marginRight: '8px' }}
                onClick={() => {
                  this.setState({ visible: true });
                }}
              >
                选择司机
              </Button>
              <Button
                onClick={this.handleUpdateLine}
                type="primary"
                style={{ marginRight: '8px', display: !this.state.updateAble && 'none' }}
              >
                更新排班
              </Button>
              <Button
                onClick={this.handleReset}
                style={{ display: !this.state.updateAble && 'none' }}
              >
                重置
              </Button>
            </div>
          }
        >
          <Form onSubmit={this.handleSubmit} layout="inline" style={{ margin: '0 12px 12px' }}>
            <FormItem label="线路名称">
              {getFieldDecorator('line', {
                initialValue: get(filterParams, 'line', ''),
              })(<Input placeholder="请输入线路进行查询" />)}
            </FormItem>
            <FormItem label="日期">
              {getFieldDecorator('whatDay', {
                initialValue: get(filterParams, 'whatDay', ''),
              })(<Input placeholder="请输入周几" />)}
            </FormItem>
            <FormItem label="方向">
              {getFieldDecorator('direction', {
                initialValue: get(filterParams, 'direction', '1'),
              })(
                <Radio.Group
                  disabled={this.state.updateAble}
                  value={get(filterParams, 'direction', '')}
                  onChange={this.handleChange}
                >
                  <Radio.Button value="1">正向</Radio.Button>
                  <Radio.Button value="0">反向</Radio.Button>
                </Radio.Group>
              )}
            </FormItem>
          </Form>
          <Table
            bordered
            rowKey="id"
            loading={this.props.loading}
            columns={columns}
            dataSource={addIndex(dataSource)}
            pagination={false}
          />
        </Card>

        <AddDriverModal
          visible={this.state.visible}
          onCancel={() => {
            this.setState({ visible: false });
          }}
          onOk={this.handleAddSite}
        />
      </div>
    );
  }
}

export default publicServerMessage;
